package com.sky.chapter1.waitAndnotify;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;

/**
 * @author : wushikai
 * <p>
 * date : 2021-03-25
 * 定义: 当缓冲区容量还剩一半  消费者们都可以同时消费, 缓冲区小于一半, ;
 */
public class ProducerConsumerPro {


    //定义一个队列缓冲区，数据为Integer
    private static Queue<Integer> queue = new LinkedList<>();

    //设置缓冲区最大容量
    private static final int MAX_SIZE = 10;

    //标志位
    static Boolean isProducer = true;

    static Boolean isConsumer = true;


    class Producer implements Runnable {


        @Override
        public void run() {

            while (true) {
                //锁住缓冲区, 防止 生产者和消费者拥挤进来;

                if (queue.size() < MAX_SIZE) { //队列小于总容量则进行生产
                    int num = new Random().nextInt(100);
                    synchronized (queue) {
                        queue.offer(num);
                        queue.notifyAll();
                        System.out.println("生产者" + Thread.currentThread().getName() + "生产了产品：" + num + "，此时缓冲区数据量为：" + queue.size());
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                } else {
                    try {
                        queue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }


        }
    }


    class Consumer implements Runnable {


        @Override
        public void run() {


        }
    }


}
